'''
Created on Apr 22, 2012

@author: KafKef
'''

import os
import thread
import sqlite3 as lite

cur_path = os.path.abspath(__file__)
cur_path = os.path.dirname(cur_path)
SERVERDB = os.path.join(cur_path, "server.db")

#print "Server db: ", SERVERDB

server_schema = """

DROP TABLE IF EXISTS Job;
DROP TABLE IF EXISTS Action;
DROP TABLE IF EXISTS Individual;
DROP TABLE IF EXISTS Archive;

CREATE TABLE Job(
    Id INTEGER PRIMARY KEY,
    Name TEXT,
    StartTime INTEGER,
    ZipData BLOB
);

CREATE TABLE Action(
    Id INTEGER,
    Object BLOB,
    JobId INTEGER,
    FOREIGN KEY(JobId) REFERENCES Job(Id)
);

CREATE TABLE Archive(
    IndId INTEGER,
    Name TEXT,
    Content BLOB,
    JobId INTEGER,
    FOREIGN KEY(JobId) REFERENCES Job(Id)
);

"""

_conn = {}

# Ensure to return a different connection object per thread.
def get_connection():
    global _conn
    tid = thread.get_ident()
    if not _conn.has_key(tid):
        _conn[tid] = lite.connect(SERVERDB)
    assert isinstance(_conn[tid], lite.Connection)
    _conn[tid].row_factory = lite.Row
    return _conn[tid]

def initialize():
    conn = lite.connect(SERVERDB)
    assert isinstance(conn, lite.Connection)
    c = conn.cursor()
    assert isinstance(c, lite.Cursor)
    c.executescript(server_schema)
    conn.commit()
    c.close()
    conn.close()

#===============================================================================
# Main for testing
#===============================================================================
def main():
    pass

if __name__ == "__main__":
    main()
